//
//  XYTOrderListViewController.m
//  XYTPayOrderSystem
//
//  Created by wupeng on 2017/8/23.
//  Copyright © 2017年 wupeng. All rights reserved.
//

#import "XYTOrderListViewController.h"
#import "XYTOrderListCell.h"
#import "XYTOrderListDetailView.h"

#define tableViewCellHeight 45.0f

@interface XYTOrderListViewController ()<UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, XYTOrderListCellDelegate>

@property (nonatomic, strong) UITextField *telNumField;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) UIView *listView;

@property (nonatomic, strong) XYTOrderListView *listHeader;

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation XYTOrderListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"订单列表";
    
    [self setupUI];
    
    [self loadData];
}

- (void)setupUI{
    UITextField *telNumField = [[UITextField alloc] initWithFrame:CGRectMake(15, 85, kScreen_Width - 15*2-40-10, 40)];
    telNumField.borderStyle = UITextBorderStyleRoundedRect;
    telNumField.font = [UIFont systemFontOfSize:16.0f];
    telNumField.textAlignment = NSTextAlignmentLeft;
    telNumField.keyboardType = UIKeyboardTypeNumberPad;
    telNumField.clearButtonMode = UITextFieldViewModeWhileEditing;
    telNumField.delegate = self;
    telNumField.placeholder = @"请输入手机号查询";
    [self.view addSubview:telNumField];
    self.telNumField = telNumField;
    
    UIButton *queryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    queryBtn.frame = CGRectMake(CGRectGetMaxX(self.telNumField.frame)+10, 85, 40, 40);
    [queryBtn.layer setBorderWidth:0.8];
    [queryBtn.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    [queryBtn.layer setCornerRadius:5.0];
    [queryBtn setImage:[UIImage imageNamed:@"searchscope"] forState:UIControlStateNormal];
    [queryBtn addTarget:self action:@selector(onClickOrderQuery) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:queryBtn];
    
    UIView *listView =[[UIView alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(self.telNumField.frame)+30, mainView_Width, kScreen_Height-CGRectGetMaxY(self.telNumField.frame)-30 -30)];
    [listView.layer setBorderWidth:1.0];
    [listView.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    [listView.layer setCornerRadius:3.0];
    listView.layer.masksToBounds = YES;
    listView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:listView];
    self.listView = listView;
    
    XYTOrderListView *listHeader = [[XYTOrderListView alloc] initWithFrame:CGRectMake(0, 0, mainView_Width, 30)];
    listHeader.backgroundColor = [UIColor colorWithRed:69.0f/255.0 green:140.0f/255.0 blue:200.0f/255.0 alpha:1];
    listHeader.separateColor = [UIColor whiteColor];;
    listHeader.telNumLab.text = @"手机号";
    listHeader.telNumLab.textColor = [UIColor whiteColor];
    listHeader.orderSumLab.text = @"订单金额";
    listHeader.orderSumLab.textColor = [UIColor whiteColor];
    listHeader.statusLab.text = @"状态";
    listHeader.statusLab.textColor = [UIColor whiteColor];
    listHeader.timeLab.text = @"时间";
    listHeader.timeLab.textColor = [UIColor whiteColor];
    [listHeader.detailBtn setTitle:@"详情" forState:UIControlStateNormal];
    [listHeader.detailBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    listHeader.detailBtn.userInteractionEnabled = NO;
    [listView addSubview:listHeader];
    self.listHeader = listHeader;
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, mainView_Width, listView.frame.size.height - 30) style:UITableViewStylePlain];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.dataSource = self;
    tableView.delegate = self;
    [listView addSubview:tableView];
    self.tableView = tableView;
}

#pragma mark - private Method
//造假数据
- (void)loadData{
    NSString *phone = [XYTUserInfoManager sharedManager].phone;
    NSString *signStr = [NSString stringWithFormat: @"%@%@%@",AppKey,AppSecret,phone];
    NSString *md5Sign = [Md5Util md5:signStr];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params xyt_setObj:phone forKey:@"phone"];
    [params xyt_setObj:md5Sign forKey:@"sign"];
    
    [self loadData:params];
}

//点击查询订单列表
- (void)onClickOrderQuery{
    NSString *phone = self.telNumField.text;
    NSString *signStr = [NSString stringWithFormat: @"%@%@%@",AppKey,AppSecret,phone];
    NSString *md5Sign = [Md5Util md5:signStr];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params xyt_setObj:phone forKey:@"phone"];
    [params xyt_setObj:md5Sign forKey:@"sign"];
    
    [self loadData:params];
    
}

- (void)loadData:(NSDictionary *)params{
    [UIView showHUD:nil];
    XYTWeakSelf(self)
    [XYTNetRequest POST:OrderListUrl parameters:params isNeedKey:NO success:^(id responseObject) {
        XYTStrongSelf(weakSelf)
        [UIView hideHUD];
        //处理数据
        [strongSelf dealWithData:responseObject];
    } failure:^(NSString *errorMsg) {
        XYTStrongSelf(weakSelf)
        [UIView hideHUD];
        [strongSelf showAlertWithTitle:errorMsg];
    }];
}



- (void)updateTableViewHeight{
    CGFloat tableHeight = self.dataSource.count*tableViewCellHeight;
    CGFloat listViewHeight = tableHeight+30;
    CGFloat listMaxHeight = kScreen_Height-CGRectGetMaxY(self.telNumField.frame)-30 -30;
    if (tableHeight > 0 &&listViewHeight<listMaxHeight) {
        self.listView.frame = CGRectMake(15, CGRectGetMaxY(self.telNumField.frame)+30, mainView_Width, listViewHeight);
    }
}

- (void)dealWithData:(id)responseObject{
    //解析数据
    NSArray *models = [XYTOrderModel mj_objectArrayWithKeyValuesArray:responseObject];
    //更新数据
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:models];
    //刷新UI
    dispatch_async(dispatch_get_main_queue(), ^{
        [self updateTableViewHeight];
        [self.tableView reloadData];
    });
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.telNumField resignFirstResponder];
}
#pragma mark - XYTOrderListCellDelegate
- (void)onClickDetail:(XYTOrderModel *)model{
    //显示详情
    [XYTOrderListDetailView showDetail:model];
}

#pragma mark - tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"XYTOrderListCell";
    XYTOrderListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[XYTOrderListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.delegate = self;
    if (indexPath.row%2 == 0) {
        cell.mainView.backgroundColor = [UIColor whiteColor];//偶数行底色是白色
    }else{
        cell.mainView.backgroundColor = [UIColor colorWithRed:248.0f/255.0 green:248.0f/255.0 blue:250.0f/255.0 alpha:1];;//奇数行底色是灰色
    }
    if (indexPath.row==self.dataSource.count - 1) {
        cell.bottomLine.hidden = NO;//最后一行的底线显示
    }
    XYTOrderModel *model = self.dataSource[indexPath.row];
    cell.orderModel = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return tableViewCellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return self.listView.frame.size.height - 30;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mainView_Width, self.listView.frame.size.height - 30)];
    footView.backgroundColor = [UIColor clearColor];
    UILabel *reminderLab = [[UILabel alloc] init];
    reminderLab.text = @"无数据";
    reminderLab.textColor =[UIColor grayColor];
    reminderLab.textAlignment = NSTextAlignmentCenter;
    CGRect rLabRect = reminderLab.frame;
    rLabRect.size = CGSizeMake(100, 20);
    reminderLab.frame = rLabRect;
    reminderLab.center = footView.center;
    [footView addSubview:reminderLab];
    footView.hidden = self.dataSource.count>0 ? YES : NO;
    return footView;
}

#pragma mark - textFieldDelgate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (string.length == 0) return YES;
    
    NSInteger existedLength = textField.text.length;
    NSInteger selectedLength = range.length;
    NSInteger replaceLength = string.length;
    if (existedLength - selectedLength + replaceLength > 11) {
        return NO;
    }
    return YES;
}

#pragma mark - setter/gerter
-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
